/**
 * Copyright (C) 2008 aileron.cc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package cc.aileron.commons.resource;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.vfs.FileContent;
import org.apache.commons.vfs.FileObject;

/**
 * classpath-resource
 * @author Aileron
 *
 */
public class ResourceImpl implements Resource
{
	/**
	 * resource
	 */
	private final FileContent content ;
	
	/**
	 * resource
	 * @param resource
	 * @throws ResourceNotFoundException
	 */
	public ResourceImpl(final FileContent content) throws ResourceNotFoundException
	{
		this.content = content;
	}
	
	
	public Properties toProperties() throws IOException
	{
		final Properties properties = new Properties();
		final InputStream stream = this.content.getInputStream();
		properties.load( stream );
		stream.close();
		
		return properties;
	}
	
	
	@Override
    public String toString()
	{
		try
		{
			return convertString();
		} 
		catch (Exception e)
		{
			return "";
		}
	}
	
	
	public FileContent toFileContent()
	{
		return content;
	}
	
	/**
	 * String に 変換
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private String convertString() throws FileNotFoundException,IOException
	{
	    final InputStreamReader ir = new InputStreamReader( content.getInputStream() );
		final StringWriter sw = new StringWriter();
		final PrintWriter pw = new PrintWriter( new BufferedWriter( sw ));
		final BufferedReader br = new BufferedReader( ir );
		while(br.ready())
		{
			pw.println( br.readLine() );
		}
		br.close(); ir.close();
		pw.flush(); pw.close();
		return sw.toString();
	}

    
    public URL toURL()
    {
        try
        {
            return content.getFile().getURL();
        }
        catch(Exception e)
        {
            return null;
        }
    }


    public FileObject toFileObject()
    {
        return this.content.getFile();
    }
}
